package com.hddznet.uniplatform.sm.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpHeaders;
import org.apache.http.message.BasicHeader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.google.gson.Gson;
import com.hddznet.uniplatform.sm.config.cas.CasConfigData;
import com.hddznet.uniplatform.sm.dto.CasToken;
import com.hddznet.uniplatform.sm.util.HdHttpUtils;
import com.hddznet.uniplatform.sm.util.HdStringUtils;
import com.hddznet.uniplatform.sm.vo.Result;

import lombok.extern.slf4j.Slf4j;

/**
 * 单点登录-客户端登录认证
 * 
 * @author 11676
 *
 */
@RestController
@RequestMapping("/cas/client")
@Slf4j
public class CasClientController {
	
	private final static String casUrl = "/hdl/oauth/v1.0/access.json";

	@Autowired
	private CasConfigData casConfigData;
	
	private Gson gson = new Gson();

	@GetMapping("/auth")
	public Object casAuthLogin(@RequestParam(name = "code", required = false) String code, @RequestParam(name = "state", required = false) String state, 
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		log.info("code={}, state={}", code, state);
		log.info("casConfigData={}", casConfigData);
		if (StringUtils.isEmpty(state)) {
			return Result.error("参数错误");
		}
		if (StringUtils.isEmpty(code)) {
			return Result.error("参数未获取");
		}
		if (!state.equals(casConfigData.getState())) {
			return Result.error("配置参数缺失");
		}
		if (casConfigData.getClientId() == null) {
			return Result.error("配置参数clientId缺失!");
		}
		if (casConfigData.getPrefixUrl() == null) {
			return Result.error("配置参数prefixUrl缺失!");
		}
		String prefixUrl = casConfigData.getPrefixUrl().trim().toLowerCase();
		if (!prefixUrl.startsWith("http")) {
			return Result.error("请检查配置参数prefixUrl");
		}
		if (prefixUrl.endsWith("/")) {
			prefixUrl = prefixUrl.substring(0, prefixUrl.length() - 1) + casUrl;
		} else {
			prefixUrl = prefixUrl + casUrl;
		}
		Map<String, String> params = new HashMap<>();
		params.put("grant_type", "authorization_code");
		params.put("client_id", casConfigData.getClientId());
		params.put("client_secret", HdStringUtils.getSHA256(casConfigData.getClientId() + "$" + casConfigData.getClientSecret()));
		params.put("redirect_uri", "http://127.0.0.1:8066/safetyManagement/cas/client/auth");
		params.put("code", code);
		Header header = new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json");
		String content = HdHttpUtils.doPost(prefixUrl, gson.toJson(params), header);
		CasToken casToken = gson.fromJson(content, CasToken.class);
		if (casToken.getAccessToken() == null) {
			return Result.error(content);
		}
		log.info("casToken={}", casToken);
		List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
		GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("user");
		grantedAuthorities.add(grantedAuthority);
		UsernamePasswordAuthenticationToken upToken = new UsernamePasswordAuthenticationToken(casToken.getUserinfo().getAccount(), "123456", grantedAuthorities);
		//final Authentication authentication = authenticationManager.authenticate(upToken);
		//SecurityContextHolder.getContext().setAuthentication(authentication);
		 
		ModelAndView modelAndView = new ModelAndView("/login");
		modelAndView.setViewName("forward:/index.html");
		return modelAndView;
	}

}
